package com.vilen.cms.controller;

import com.vilen.cms.auth.AuthMethod;
import com.vilen.cms.model.Role;
import com.vilen.cms.model.RoleType;
import com.vilen.cms.model.User;
import com.vilen.cms.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by vilen on 2017/2/15.
 */
@Controller
public class LoginController {
    private IUserService userService;

    public IUserService getUserService() {
        return userService;
    }

    @Inject
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "admin/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, String password, Model model, HttpSession session) {
        //todo 验证码

        User loginUser = userService.login(username, password);
        session.setAttribute("loginUser", loginUser);

        List<Role> rs = userService.listUserRoles(loginUser.getId());
        boolean isAdmin = isAdmin(rs);
        session.setAttribute("isAdmin", isAdmin);
        if(!isAdmin){
            session.setAttribute("allActions",getAllActions(rs,session));
        }
        return "redirect:/admin";
    }



    private Set<String> getAllActions(List<Role> rs, HttpSession session) {
        Set<String> actions = new HashSet<String>();
        Map<String, Set<String>> allAuths = (Map<String, Set<String>>) session.getServletContext().getAttribute("allAuths");
        actions.addAll(allAuths.get("base"));
        for (Role r : rs) {
            if (r.getRoleType() == RoleType.ROLE_ADMIN) {
                continue;
            }
            actions.addAll(allAuths.get(r.getRoleType().name()));
        }
        return actions;
    }

    private boolean isAdmin(List<Role> rs) {
        for (Role r : rs) {
            if (r.getRoleType() == RoleType.ROLE_ADMIN) {
                return true;
            }
        }
        return false;
    }
}
